from collections import OrderedDict
import os
from datetime import datetime

from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from django.conf import settings
from apps import redis_client
from .serializer import *
from util.auth import OWNTokenAuthentication
from util.page import MyPageNumberPagination
from util.exception import ValidationError


class ZhuChengXuViewset(GenericViewSet):
    authentication_classes = [OWNTokenAuthentication]

    @action(detail=False, methods=["GET", ], url_path="files_list")
    def files_list(self, requests, *args, **kwargs):
        file_path = settings.CONFIG_FILE_PATH
        if not os.path.isdir(file_path):
            os.mkdir(file_path)
        files = os.listdir(file_path)
        results = []
        for name in files:
            results.append({
                "key": name,
                "name": name
            })
        return Response({
            "code": 200,
            "result": results
        })

    @action(detail=False, methods=["POST", ], url_path="files_upload")
    def files_write(self, requests, *args, **kwargs):
        file_path = settings.CONFIG_FILE_PATH
        if not os.path.isdir(file_path):
            os.mkdir(file_path)
        myFile = requests.FILES.get("file")
        if not myFile:
            raise ValidationError(50002)
        name = myFile.name
        destination = open(os.path.join(file_path, name), "wb+")
        for chunk in myFile.chunks():
            destination.write(chunk)
        destination.close()
        return Response({
            "code": 200,
            "msg": "上传成功"
        })

    @action(detail=False, methods=["POST", ], url_path="files_delete")
    def files_delete(self, requests, *args, **kwargs):
        data = {}
        data["files"] = requests.data.get("files")
        serializers = ScriptsFileDeleteSeriallizer(data=data)
        if serializers.is_valid():
            files = serializers.validated_data.get("files", [])
            file_path = settings.CONFIG_FILE_PATH
            if not os.path.isdir(file_path):
                os.mkdir(file_path)
            for file in files:
                delete_path = "".join([file_path, "/", file])
                if os.path.exists(delete_path):
                    os.remove(delete_path)
            return Response({
                "code": 200,
                "msg": "删除成功"
            })
        else:
            raise ValidationError(20001)

    @action(detail=False, methods=["POST", ], url_path="update_files_delete")
    def files_delete(self, requests, *args, **kwargs):
        data = {}
        data["files"] = requests.data.get("files")
        serializers = ScriptsFileDeleteSeriallizer(data=data)
        if serializers.is_valid():
            files = serializers.validated_data.get("files", [])
            file_path = settings.UPDATE_GATEWAY_FILE_PATH
            if not os.path.isdir(file_path):
                os.mkdir(file_path)
            for file in files:
                delete_path = "".join([file_path, "/", file])
                if os.path.exists(delete_path):
                    os.remove(delete_path)
            file_path = settings.UPDATE_SENSOR_FILE_PATH
            if not os.path.isdir(file_path):
                os.mkdir(file_path)
            for file in files:
                delete_path = "".join([file_path, "/", file])
                if os.path.exists(delete_path):
                    os.remove(delete_path)
            return Response({
                "code": 200,
                "msg": "删除成功"
            })
        else:
            raise ValidationError(20001)
